package com.czxy.common.util;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * @author likk
 * @create 2018/7/27
 */
public class DateUtil {

    /**
     * 将时间戳转换为日期
     * @param time
     * @return
     */
    public static Date timestampToDate(Long time) {
        if (time != null) {
            return new Date(time * 1000);
        }
        return null;
    }

    /**
     * 获取指定时间时间戳，精确到秒
     *
     * @param date
     * @return
     */
    public static long getStringToDate(Date date) {

        if (date != null) {
            return date.getTime() / 1000;
        }
        return 0;
    }

    /**
     * 获取当前时间时间戳，精确到秒
     * @return
     */
    public static long getTimeStamp() {
        return System.currentTimeMillis() / 1000;
    }

    /**
     * 计算两个日期之间相差的天数
     * @param smallDate 较小的时间
     * @param maxDate  较大的时间
     * @return 相差天数
     * @throws ParseException
     * calendar 对日期进行时间操作
     * getTimeInMillis() 获取日期的毫秒显示形式
     */
    public static int daysBetween(Date smallDate,Date maxDate) throws ParseException
    {
        Calendar cal = Calendar.getInstance();
        cal.setTime(smallDate);
        long time1 = cal.getTimeInMillis();
        cal.setTime(maxDate);
        long time2 = cal.getTimeInMillis();
        long between_days=(time2-time1)/(1000*3600*24);
        return Integer.parseInt(String.valueOf(between_days));
    }
    /**
     * 字符串日期格式的计算
     * @param smdate
     * @param bdate
     * @return
     * @throws ParseException
     */
    public static int daysBetween(String smdate,String bdate) throws ParseException{
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
        Calendar cal = Calendar.getInstance();
        cal.setTime(sdf.parse(smdate));
        long time1 = cal.getTimeInMillis();
        cal.setTime(sdf.parse(bdate));
        long time2 = cal.getTimeInMillis();
        long between_days=(time2-time1)/(1000*3600*24);
        return Integer.parseInt(String.valueOf(between_days));
    }
    /**
     * 字符串日期格式和date日期格式的计算
     * @param smdate
     * @param bdate
     * @return
     * @throws ParseException
     */
    public static int daysBetween(String smdate,Date bdate) throws ParseException {
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
        Calendar cal = Calendar.getInstance();
        cal.setTime(sdf.parse(smdate));
        long time1 = cal.getTimeInMillis();
        cal.setTime(bdate);
        long time2 = cal.getTimeInMillis();
        long between_days=(time2-time1)/(1000*3600*24);
        return Integer.parseInt(String.valueOf(between_days));
    }

}
